package com.javaex.book.service.impl;

import java.util.List;

import com.javaex.book.dao.UserDao;
import com.javaex.book.dao.impl.UserDaoImpl;
import com.javaex.book.pojo.User;
import com.javaex.book.service.UserService;
import com.javaex.book.utils.MD5Utils;
import com.javaex.book.utils.ReturnResult;

public class UserServiceImpl implements UserService {
	
	private UserDao userDao = new UserDaoImpl();
	
	@Override
	public ReturnResult register(User user) {
		ReturnResult result = new ReturnResult();
		if (userDao.queryUserByUsernameOrEmail(user.getUsername(), user.getEmail()) != null) {
			return result.fail("用户名或邮箱已被使用");
		}
		// 对密码进行md5加密
		user.setPassword(MD5Utils.md5(user.getPassword()));
		int rows = userDao.saveUser(user);
		if (rows > 0) {
			return result.success("注册成功");
		} 
		return result.fail();
	} 

	@Override
	public ReturnResult login(String username, String password) {
		ReturnResult result = new ReturnResult();
		User user = userDao.queryUserByUsername(username);
		if (user == null) {
			return result.fail("用户不存在");
		} 
		if (!user.getPassword().equals(MD5Utils.md5(password)))  {
			return result.fail("密码错误");
		}
		result.setData(user);
		return result.success();
	}

	@Override
	public boolean existsByUsernameOrEmail(String username, String email) {
		return !(userDao.queryUserByUsernameOrEmail(username, email) == null);
	}

	@Override
	public Integer countUsers() {
		return userDao.countUsers();
	}
	
	@Override
	public List<User> queryUserList(Integer start, Integer pageSize) {
		return userDao.queryUserList(start, pageSize);
	}
	
	@Override
	public Integer updateUser(User user) {
		if (user.getPassword() != null && !user.getPassword().isEmpty()) {
			// 对密码进行md5加密
			user.setPassword(MD5Utils.md5(user.getPassword()));
		}
		return userDao.updateUser(user);
	}
	
	@Override
	public User queryUserById(Integer id) {
		return userDao.queryUserById(id);
	}
	
	@Override
	public Integer deleteUser(Integer id) {
		return userDao.deleteUser(id);
	}
}
